<?php
/*
 module:		会员充值订单
 create_time:	2022-04-05 20:59:05
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\service\ZhMatchmakerLevelOrderService;
use app\backend\model\ZhMatchmakerLevelOrder as ZhMatchmakerLevelOrderModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\api\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\api\model\ZhMatchmaker as ZhMatchmakerModel;
use app\api\service\PaymentService;

class ZhMatchmakerLevelOrder extends Common
{

    function test(){
        $res=file_put_contents('a.txt','  vvvvvvv' . date('Y_m_d'),FILE_APPEND);
        print_r($res);
    }

    function index()
    {
        $wxapp_id = $this->request->get('wxapp_id');
        $l_id      = $this->request->get('l_id');
        $m_id      = $this->request->get('m_id');
        $status  = $this->request->get('status');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

       /* $authentication = \app\api\model\ZhAuthentication::where(['id' => $a_id, 'wxapp_id' => $wxapp_id])->find();
        if (!$authentication) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }*/
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');
        $where             = [];
        $where['o.wxapp_id'] = $wxapp_id;
        if($status){
            $where['o.status']   = $status;
        }
        if($l_id){
            $where['o.l_id']     = $l_id;
        }
        if($m_id){
            $where['o.m_id']     = $m_id;
        }
        $res = ZhMatchmakerLevelOrderService::indexList(formatWhere($where), $limit, $page);
        foreach ($res['rows'] as &$v) {
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            if($v['updatetime']){
                $v['updatetime'] = date('Y-m-d H:i:s', $v['updatetime']);
            }
        }
        return $this->ajaxReturn($this->successCode, '返回成功', htmlOutList($res));
    }


    function view()
    {
        $id= $this->request->get('id');
        if(!$id) $this->error('参数错误');
        $sql = 'select  o.id,o.m_id, o.price,o.status,o.order_sn, o.createtime,
                gc_zh_matchmaker.name  m_name,l.id l_id,l.name l_name
                from gc_zh_matchmaker_level_order  as o  
                left join gc_zh_matchmaker  on o.m_id=gc_zh_matchmaker.matchmaker_id
                left join gc_zh_matchmaker_level  l on  o.l_id=l.id
                where o.id = '.$id.' limit 1';
        $info = Db::connect('mysql')->query($sql)[0];

        $info["createtime"]=date("Y-m-d H:i:s",$info["createtime"]);

        return $this->ajaxReturn($this->successCode, '返回成功', $info);
    }
    //发起订单
    function add()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $m_id     = $this->request->post('m_id');
        $l_id     = $this->request->post('l_id');
        $price= $this->request->post('price');

        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }else{
            $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
            if (!$wxSetting) {
                return $this->ajaxReturn($this->errorCode, '平台参数未配置');
            }
        }

        if (!$m_id) {
            return $this->ajaxReturn($this->errorCode, '缺少红娘id参数');
        }else{
            $matchmaker=\app\api\model\ZhMatchmaker::find($m_id);
            if (!$matchmaker) {
                return $this->ajaxReturn($this->errorCode, '未知红娘用户');
            }
        }
        //获取用户open_id
        $open_id="";
        $token = $this->request->header('Authorization');
        $uid   = 0;
        $op=$this->request->post('op');
        if($op=="lwxtest"){
            $open_id="oO_Sz68NYWAjt63SENKnqfiV0SRA";
        }else{
            if ($token) {
                $jwt = Jwt::getInstance();
                $jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))
                    ->setSecrect(config('my.jwt_secrect'))
                    ->setToken($token);
                $uid  = $jwt->decode()->getClaim('uid');
                $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
                if (!$user) {
                    return $this->ajaxReturn($this->errorCode, '会话过期，请重新登陆');
                }
                $open_id=$user["openid"];
            }else{
                return $this->ajaxReturn($this->errorCode, 'token过期，请重新登陆');
            }
        }

        if(!$open_id){
            return $this->ajaxReturn($this->errorCode, '没有获取到用户的openid,请重新登陆~');
        }
        $zhmatchmakerLevelOrderId =ZhMatchmakerLevelOrderModel::insertGetId([
            'wxapp_id'         => $wxapp_id,
            'order_sn'         => $m_id . '0' . $wxapp_id . time() . rand(100, 999),
            'status'           => 0,
            'm_id'             => $m_id,
            'l_id'             => $l_id,
            'price'            => $price,
            'open_id'          => $open_id,
            'createtime'       => time()
        ]);
        if ($zhmatchmakerLevelOrderId) {
            return $this->ajaxReturn($this->successCode, '操作成功', ['order_id' => $zhmatchmakerLevelOrderId]);
        }else{
            return $this->ajaxReturn($this->errorCode, '操作失败');
        }

    }


    /**
     * 发起支付
     *
     *
     * @author lwx
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function pay()
    {
        $id       = $this->request->post('id' );
        $type     = $this->request->post('type', 'wx', 'serach_in');
        $OrderData=ZhMatchmakerLevelOrderModel::find($id);
        if (!$OrderData) {
            return $this->ajaxReturn($this->errorCode, '订单不存在');
        }
        $wxapp_id=$OrderData["wxapp_id"];
        $pay_price=$OrderData["price"];
        $openId=$OrderData["open_id"];
        $order_sn=$OrderData["order_sn"];
        file_put_contents('a.txt','发起支付订单'.$id .   date('Y_m_d H:i:s'),FILE_APPEND);
        try {
            //支付回调的地址
            $notify_url = 'http://' . $_SERVER['HTTP_HOST'] . '/api/ZhMatchmakerLevelOrder/payResult/wxapp_id/' . $wxapp_id;
            if ($type == 'wx') {
                $trade_type = 'JSAPI';
            } elseif ($type == 'app') {
                $trade_type = 'APP';
            } elseif ($type == 'H5') {
                $trade_type = 'MWEB';
            } elseif ($type == 'H5-wx') {
                $trade_type     = 'JSAPI';
//                    $user['openid'] = $user['official_account_openid'];
            }
            //生成支付链接
            $js_pay = PaymentService::instance($wxapp_id, $type)->create($openId, $order_sn, $pay_price, '红娘招商代理升级付费', ['notify_url' => $notify_url], $trade_type);
            return $this->ajaxReturn($this->successCode, '操作成功', ['order' => $OrderData['order_sn'], 'paydata' => $js_pay]);
        } catch (\Exception $e) {
            return $this->ajaxReturn($this->errorCode, $e->getMessage());
        }
    }

    // 支付回调
    public function payResult()
    {
        $wxapp_id = input('wxapp_id');
        file_put_contents('log.txt','进入回调' . date('Y_m_d'));
        $app      = PaymentService::instance($wxapp_id)::getPayApp();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($wxapp_id) {
            trace($message, 'notify_' . date('Y_m_d'));
            $order = ZhMatchmakerLevelOrderModel::where(['order_sn' => $message['out_trade_no']])->find();
            if (!$order || $order->status == 1) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                file_put_contents('a.txt','支付成功 SUCCESS' .   date('Y_m_d H:i:s'),FILE_APPEND);

                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //1、修改订单支付状态
                    ZhMatchmakerLevelOrderModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status' => 1,'updatetime'=>time()]);
                    //2、修改红娘等级id
                    $m_id=$order["m_id"];
                    $level_id=$order["l_id"];
                    ZhMatchmakerModel::where(["matchmaker_id"=>$m_id])->update(['level_id' => $level_id,'status'=>1]);
                    file_put_contents('a.txt','修改订单status' .   date('Y_m_d H:i:s'),FILE_APPEND);

                   /* ZhmPayLogModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status' => 1, 'wx_order_sn' => $message['transaction_id']]);*/
                   // file_put_contents('a.txt','修改mpaylog' .   date('Y_m_d H:i:s'),FILE_APPEND);

                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response->send(); // return $response;
    }



}

